package com.ray.service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.ray.bean.*;
import com.ray.exception.ServiceException;
import com.ray.mapper.AirFlowControlMapper;
import com.ray.mapper.AirFlowControlRelationEquipmentMapper;
import com.ray.mapper.AirFlowControlRelationTimeIntervalMapper;
import com.ray.mapper.TemporalIntervalMapper;
import com.ray.pojo.AirFlowControlPojo;
import com.ray.util.ReturnStringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Service
public class AirFlowControlService {

	@Autowired
	private AirFlowControlMapper airFlowControlMapper;

	@Autowired
	private AirFlowControlRelationEquipmentMapper airFlowControlRelationEquipmentMapper;

	@Autowired
	private AirFlowControlRelationTimeIntervalMapper airFlowControlRelationTimeIntervalMapper;

	@Autowired
	private TemporalIntervalMapper temporalIntervalMapper;

	/**
	 * 
	 * @Title: addAirFlowControl  
	 * @author: 李宇航
     * @Description: 添加空气流量控制开关
	 * @param: @param requestParamMap
	 * @param: @return
	 * @param: @throws ServiceException      
	 * @return: String      
	 * @throws
	 */
	public String addAirFlowControl(Map<String, String> requestParamMap)
			throws ServiceException {
		String equiptments = requestParamMap.get("equiptments");//空气流量开关绑定的设备
		List<String> equiptmentIds = JSON.parseArray(equiptments, String.class);
		//将map里的信息转换为bean
		AirFlowControlBean airFlowControlBean = new AirFlowControlBean(
				requestParamMap);
		//处理空气流量器和设备关系，一个设备只能关联一个开关
		handleAirFlowControlRelationEquiptment(equiptmentIds,
				airFlowControlBean);

		List<String> temporalIntervals = JSON.parseArray(
				requestParamMap.get("temporalInterval"), String.class);
		List<TemporalIntervalBean> temporalIntervalBeans = new ArrayList<>();
		for (String temporalInterval : temporalIntervals) {
			JSONObject jsonObject = JSON.parseObject(temporalInterval);
			temporalIntervalBeans.add(new TemporalIntervalBean(jsonObject
					.getString("startTime"), jsonObject.getString("endTime")));
		}
		handleAirFlowControlRelationTimeInterval(temporalIntervalBeans,
				airFlowControlBean);
		//保存空气开关信息
		airFlowControlMapper.insertAirFlowControl(airFlowControlBean);
		return ReturnStringUtil.CREATE_SUCCESS;

	}

	/**
	 * 修改空气流量开关信息
	 * @param requestParamMap
	 * @return
	 * @throws ServiceException
	 */
	public String updateAirFlowControl(Map<String, String> requestParamMap)
			throws ServiceException {
		//获取空气流量开关信息，不带一对多信息
		AirFlowControlBean airFlowControlBean = airFlowControlMapper
				.getAirFlowControlBeanById(requestParamMap
						.get("airFlowControlId"));
		//修改空气流量控制开关信息
		airFlowControlMapper.updataAirFlowControl(airFlowControlBean
				.updateSelf(requestParamMap));
		//有修改设备，删除之前关联的所有设备，重新添加
		if (requestParamMap.get("equiptments") != null
				&& !"".equals(requestParamMap.get("equiptments"))) {
			airFlowControlRelationEquipmentMapper
			.delByAirFlowControl(airFlowControlBean
					.getAirFlowControlId());
			List<String> equiptmentIds = JSON.parseArray(
					requestParamMap.get("equiptments"), String.class);
			handleAirFlowControlRelationEquiptment(equiptmentIds,
					airFlowControlBean);
		}
		//如果有修改时间，删除之前关联的所有时间，重新关联
		if (requestParamMap.get("temporalInterval") != null
				&& !"".equals(requestParamMap.get("temporalInterval"))) {
			List<String> temporalIntervals = JSON.parseArray(
					requestParamMap.get("temporalInterval"), String.class);
			List<TemporalIntervalBean> temporalIntervalBeans = new ArrayList<>();
			for (String temporalInterval : temporalIntervals) {
				JSONObject jsonObject = JSON.parseObject(temporalInterval);
				temporalIntervalBeans.add(new TemporalIntervalBean(jsonObject
						.getString("startTime"), jsonObject
						.getString("endTime")));
			}
			airFlowControlRelationTimeIntervalMapper.delByAirFlowControl(airFlowControlBean
					.getAirFlowControlId());
			handleAirFlowControlRelationTimeInterval(temporalIntervalBeans,
					airFlowControlBean);
		}
		return ReturnStringUtil.UPDATE_SUCCESS;

	}

	/**
	 * 删除空气流量控制开关
	 * @param requestParamMap
	 * @return
	 * @throws ServiceException
	 */
	public String delAirFlowControl(Map<String, String> requestParamMap)
			throws ServiceException {
		String airFlowControlId = requestParamMap.get("airFlowControlId");
		//如果不存在就直接返回删除成功了~~~~~
		if (airFlowControlMapper.getAirFlowControlBeanById(airFlowControlId) != null) {
			airFlowControlMapper.delByControlSwitchId(airFlowControlId);
			airFlowControlRelationEquipmentMapper
					.delByAirFlowControl(airFlowControlId);
			airFlowControlRelationTimeIntervalMapper
					.delByAirFlowControl(airFlowControlId);
		}
		return ReturnStringUtil.DELETE_SUCCESS;

	}

	public List<AirFlowControlBean> selectAirFlowControl(
			Map<String, String> requestParamMap) throws ServiceException {
		return airFlowControlMapper
				.getAirFlowControlBeansByCompany(requestParamMap
						.get("loginCompany"));

	}

	/**
	 * 查询空气流量控制信息
	 * @isUrl true
	 * @param requestParamMap
	 * @return
	 * @throws ServiceException
	 */
	public DatatablesViewPageBean<AirFlowControlPojo> selectAirFlowControlByPage(
			Map<String, String> requestParamMap) throws ServiceException {
		int currentPage = Integer.valueOf(requestParamMap.get("currentPage")
				.trim());
		int pageSize = Integer.valueOf(requestParamMap.get("pageSize").trim());
		int start = (currentPage - 1) * pageSize;
		int end = start + pageSize;
		DatatablesViewPageBean<AirFlowControlPojo> datatablesViewPageBean = new DatatablesViewPageBean<>();
		datatablesViewPageBean.setReturnData(airFlowControlMapper
				.getAirFlowControlPojoByPageAndCompany(
						requestParamMap.get("loginCompany"), start, end));
		datatablesViewPageBean.setiTotalRecords(selectAirFlowControl(
				requestParamMap).size());
		return datatablesViewPageBean;

	}

	/**
	 * 处理空气流量控制开关时间
	 * @param temporalIntervalBeans
	 * @param airFlowControlBean
	 */
	private void handleAirFlowControlRelationTimeInterval(
			List<TemporalIntervalBean> temporalIntervalBeans,
			AirFlowControlBean airFlowControlBean) {
		for (TemporalIntervalBean temporalIntervalBean : temporalIntervalBeans) {
			//获取这两个时间的id，同一个时间区间不用报保存多次
			String temporalIntervalId = temporalIntervalMapper
					.getTemporalIntervalId(temporalIntervalBean.getStartTime(),
							temporalIntervalBean.getEndTime());
			//如果时间区间有记录
			if (temporalIntervalId != null) {
                //如果时间区间和开关已经关联过，跳过不处理
				if (airFlowControlRelationTimeIntervalMapper
						.getAirFlowControlRelationTimeInterval(
								temporalIntervalId,
								airFlowControlBean.getAirFlowControlId()) != null) {
					continue;
				}
				//保存关联关系
				AirFlowControlRelationTimeIntervalBean airFlowControlRelationTimeIntervalBean = new AirFlowControlRelationTimeIntervalBean(
						temporalIntervalId,
						airFlowControlBean.getAirFlowControlId());
				airFlowControlRelationTimeIntervalMapper
						.insertAirFlowControlRelationTimeInterval(airFlowControlRelationTimeIntervalBean);
			} else {//时间区间没有记录，先保存时间区间，再保存关联关系
				temporalIntervalMapper
						.insertTemporalInterval(temporalIntervalBean);
				AirFlowControlRelationTimeIntervalBean airFlowControlRelationTimeIntervalBean = new AirFlowControlRelationTimeIntervalBean(
						temporalIntervalBean.getTimeIntervalId(),
						airFlowControlBean.getAirFlowControlId());
				airFlowControlRelationTimeIntervalMapper
						.insertAirFlowControlRelationTimeInterval(airFlowControlRelationTimeIntervalBean);
			}

		}
	}

	/**
	 * 处理空气流量控制器和设备关系
	 * @param equiptmentIds 
	 * @param airFlowControlBean
	 */
	private void handleAirFlowControlRelationEquiptment(
			List<String> equiptmentIds, AirFlowControlBean airFlowControlBean) {
		Assert.notNull(airFlowControlBean.getControlSwitchId(), "空气流量控制开关id为空");
		Assert.notNull(equiptmentIds, "未获取到关联设备");
		for (String equiptmentId : equiptmentIds) {
			//如果有关联过空气流量控制器，就不做处理（一个设备只能挂关联一个开关）
			if (airFlowControlRelationEquipmentMapper
					.getByEquiptment(equiptmentId) != null) {
				continue;
			}
			//没有关联过则直接保存记录
			AirFlowControlRelationEquipmentBean airFlowControlRelationEquipmentBean = new AirFlowControlRelationEquipmentBean(
					airFlowControlBean.getAirFlowControlId(), equiptmentId);
			airFlowControlRelationEquipmentMapper
					.insertAirFlowControlRelationEquipment(airFlowControlRelationEquipmentBean);
		}
	}
}
